﻿using LearningEnglish.ViewModels;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LearningEnglish.Controllers
{
    public class CheckTokenAttribute : ActionFilterAttribute
    {
        public CheckTokenAttribute()
        {
            Order = 0;
        }

        protected virtual Guid GetTicket(ActionExecutingContext filterContext)
        {
            var ticket = filterContext.HttpContext.Request.Form["___ticket"];
            if (string.IsNullOrWhiteSpace(ticket))
                throw new Exception("未获取到访问票据");
            Guid temp;
            if (!Guid.TryParse(ticket, out temp))
                throw new Exception("票据内容格式不正确");
            return Guid.Parse(ticket);
        }

        protected virtual bool VaildTicket(Guid ticket)
        {
            var tokenRD = (from p in VM.Tokens where p.Has(ticket) select p).Single();
            return !tokenRD.IsTimeOut(ticket);
        }

        protected virtual void HandleNoTicket(ActionExecutingContext filterContext)
        {
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 401;

            filterContext.Result = new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new
                {
                    error = true,
                    msg = "访问权限不足"
                }
            };
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var isVaild = VaildTicket(GetTicket(filterContext));
            if (!isVaild)
                HandleNoTicket(filterContext);
            else
                base.OnActionExecuting(filterContext);
        }
    }
}